package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.*;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @ClassName: AggsTvsSearch
 * @author: BANG
 * @Date: 2020/01/15 13:56
 * @Version: 1.0
 * @Modified By:
 * @Desc:
 *
 *GET /tvs/sales/_search
 * {
 *    "size" : 0,
 *    "aggs": {
 *       "sales": {
 *          "date_histogram": {
 *             "field": "sold_date",
 *             "interval": "month",
 *             "format": "yyyy-MM-dd",
 *             "min_doc_count" : 0,
 *             "extended_bounds" : {
 *                 "min" : "2016-01-01",
 *                 "max" : "2017-12-31"
 *             }
 *          }
 *       }
 *    }
 * }
 */
public class DateHistogramTvsSearch {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("tvs").setTypes("sales")
                .addAggregation(AggregationBuilders.dateHistogram("sales")
                                .field("sold_date")
                                .format("yyyy-MM-dd")
                                .minDocCount(0L)
                                .dateHistogramInterval(DateHistogramInterval.MONTH)
                                .extendedBounds(new ExtendedBounds("2016-01-01","2017-12-31"))
                                )
                .setSize(0)
                .get();


        Aggregations aggregations = searchResponse.getAggregations();
        InternalDateHistogram dateHistogram = aggregations.get("sales");
        List<Histogram.Bucket> buckets = dateHistogram.getBuckets();
        for (Histogram.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            System.out.println(keyAsString+"=="+docCount);
        }
        client.close();

    }
}
